package com.icode.web.controller;

import com.icode.core.shared.ImageUtils;
import com.icode.service.house.HouseService;
import com.icode.service.user.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import sun.awt.AppContext;
import sun.awt.SunToolkit;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletResponse;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;

/**
 * Created with IntelliJ IDEA.
 * User: xianfei
 * Date: 15-4-28
 * Time: 上午9:42
 * To change this template use File | Settings | File Templates.
 */
@Controller
@RequestMapping("/public")
public class PublicController {

    @Autowired
    private HouseService houseService;

    @RequestMapping(value = "image/{guid}", method = RequestMethod.GET)
    public void showImage(@PathVariable String guid, HttpServletResponse response) {
        byte[] contents = houseService.getImageByGuid(guid);
        ImageUtils.showImageByContents(contents, response);
    }

    @RequestMapping(value = "img/{guid}/{width}/{height}", method = RequestMethod.GET)
    public void testImg(@PathVariable String guid, @PathVariable String width, @PathVariable String height, HttpServletResponse response) {
        try {
            byte[] contents = houseService.getImageByGuid(guid);
            InputStream is = new ByteArrayInputStream(contents);
            if (AppContext.getAppContext() == null) {
                SunToolkit.createNewAppContext();
            }
            BufferedImage bufferedImage = ImageIO.read(is);
            ImageUtils.resize(Integer.parseInt(width), Integer.parseInt(height), bufferedImage, response);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @RequestMapping(value = "src_img/{guid}", method = RequestMethod.GET)
    public void sourceImageHandle(@PathVariable String guid, HttpServletResponse response) {
        try {       // 根据原图尺寸压缩
            byte[] contents = houseService.getImageByGuid(guid);
            InputStream is = new ByteArrayInputStream(contents);
            if (AppContext.getAppContext() == null) {
                SunToolkit.createNewAppContext();
            }
            BufferedImage bufferedImage = ImageIO.read(is);
            ImageUtils.resize(bufferedImage.getWidth(), bufferedImage.getHeight(), bufferedImage, response);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

}
